package com.ken.task;

import com.ken.entity.Orders;
import com.ken.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.ken.entity.Orders.COMPLETED;
import static com.ken.entity.Orders.DELIVERY_IN_PROGRESS;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderService orderService;

    @Scheduled(cron="0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("订单超时成立时间：{}", LocalDateTime.now());
        List<Orders> list = orderService
                .lambdaQuery()
                .le(Orders::getOrderTime, LocalDateTime.now().minusMinutes(15))
                .list();
        List<Orders> updateList = new ArrayList<>();
        if (list!=null&&!list.isEmpty()) {
            for (Orders orders:list){
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时，自动取消");
                orders.setStatus(Orders.CANCELLED);
                updateList.add(orders);
            }
            orderService.updateBatchById(updateList);
        }
    }

    //派送中状态的订单处理
    @Scheduled(cron="0 0 5 * * ?")
    public void deliveryInProgressOrder() {
        log.info("处理派送中的订单时间{}",LocalDateTime.now());
        List<Orders> list = orderService.lambdaQuery()
                .eq(Orders::getStatus, DELIVERY_IN_PROGRESS)
                .list();
        ArrayList<Orders> deliveryInProgressOrderList = new ArrayList<>();
        if (list != null&&!list.isEmpty()){
            for (Orders orders:list){
                orders.setStatus(COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                deliveryInProgressOrderList.add(orders);
            }
            orderService.updateBatchById(deliveryInProgressOrderList);
        }
    }
}
